package com.zwk.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwk.common.utils.PageUtils;
import com.zwk.common.utils.Query;
import com.zwk.gulimall.product.annotation.Overall;
import com.zwk.gulimall.product.dao.BrandDao;
import com.zwk.gulimall.product.entity.BrandEntity;
import com.zwk.gulimall.product.entity.CategoryEntity;
import com.zwk.gulimall.product.service.BrandService;
import com.zwk.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.Map;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService, ApplicationContextAware {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    private ApplicationContext context;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<BrandEntity> query = new LambdaQueryWrapper<>();
        query.and((obj)->{
            Object key = params.get("key");
            obj.eq(BrandEntity::getBrandId,key).or().like(BrandEntity::getName,key);
        });

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                query
        );
        return new PageUtils(page);
    }

    /**
     * @Overall ：更新冗余字段
     * @param brandEntity
     */
    @Override
    @Transactional
//    @TransactionalEventListener   //这个注解不是添加事务
    public void updateDetail(BrandEntity brandEntity) {
        this.updateById(brandEntity);
        context.publishEvent(brandEntity);

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context=applicationContext;
    }
}